import _thread
from time import sleep

import cv2
from flask import render_template, Response, Flask

from py_code.driver.Camera import Camera
from py_code.driver.DriverManager import getDriver
from py_code.util.logger import defalutLogConfig

defalutLogConfig()


class VideoNet:
    """
    发送视频数据的网络
    """
    camera: Camera

    def __init__(self, camera):
        self.camera = camera

    def gen_frames(self):
        while True:
            print('start read')
            success, img = self.camera.read()  # read the camera frame
            if not success:
                break
            else:
                print('start encode')
                ret, buffer = cv2.imencode('.jpg', img)
                frame = buffer.tobytes()
                print('start show')
                cv2.imshow('img', img)
                print('start wait')
                cv2.waitKey(24)
                # yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'


app = Flask(__name__)


@app.route('/')
def video_index():
    return render_template('index.html')


video_net = VideoNet(getDriver(Camera()))


@app.route('/video_feed')
def video_feed():
    return Response(video_net.gen_frames(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


def start():
    app.run()


if __name__ == '__main__':
    video_net.gen_frames()
